package com.cicc.beergamevirtualsimulationsystem.interceptor;

import com.cicc.beergamevirtualsimulationsystem.context.BaseContext;
import com.cicc.beergamevirtualsimulationsystem.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清除用户信息
        BaseContext.removeCurrentId();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("token");
        // 检查 Token 是否为空
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token is null");
            return false;
        }
        //检查token是否过期
        try {
            JwtUtil.isTokenExpired(token);
        }catch (Exception e){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid or expired token");
            return false;
        }
        BaseContext.setCurrentId(JwtUtil.extractUserId(token));
        return true;

    }
}
